using System;
using System.IO;
using System.Text;
using System.Diagnostics;

namespace GameOverlayWPF
{
    /// <summary>
    /// 启动诊断工具，用于记录启动过程中的关键信息和错误
    /// </summary>
    public static class StartupDiagnostics
    {
        private static readonly string LogFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "GameOverlayWPF",
            "startup_log.txt"
        );

        private static readonly object _lockObject = new object();
        private static bool _isInitialized = false;

        /// <summary>
        /// 初始化诊断日志
        /// </summary>
        public static void Initialize()
        {
            if (_isInitialized) return;

            try
            {
                var directory = Path.GetDirectoryName(LogFilePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 清理旧日志（保留最近3天）
                CleanOldLogs(directory);

                // 写入启动标记
                var startupInfo = new StringBuilder();
                startupInfo.AppendLine($"========== 启动诊断日志 ==========");
                startupInfo.AppendLine($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                startupInfo.AppendLine($"操作系统: {Environment.OSVersion}");
                startupInfo.AppendLine($".NET版本: {Environment.Version}");
                startupInfo.AppendLine($"工作目录: {Environment.CurrentDirectory}");
                startupInfo.AppendLine($"用户: {Environment.UserName}");
                startupInfo.AppendLine("=====================================");

                File.WriteAllText(LogFilePath, startupInfo.ToString());
                _isInitialized = true;

                Debug.WriteLine($"启动诊断日志已初始化: {LogFilePath}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"初始化启动诊断日志失败: {ex.Message}");
                // 不抛出异常，确保应用能继续启动
            }
        }

        /// <summary>
        /// 记录启动步骤
        /// </summary>
        public static void LogStep(string step, string details = "")
        {
            if (!_isInitialized) return;

            try
            {
                lock (_lockObject)
                {
                    var logEntry = $"[{DateTime.Now:HH:mm:ss.fff}] {step}";
                    if (!string.IsNullOrEmpty(details))
                    {
                        logEntry += $" - {details}";
                    }
                    logEntry += Environment.NewLine;

                    File.AppendAllText(LogFilePath, logEntry);
                    Debug.WriteLine($"[诊断] {logEntry.TrimEnd()}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"写入启动日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 记录错误
        /// </summary>
        public static void LogError(string context, Exception ex)
        {
            if (!_isInitialized) return;

            try
            {
                lock (_lockObject)
                {
                    var errorLog = new StringBuilder();
                    errorLog.AppendLine($"[{DateTime.Now:HH:mm:ss.fff}] ❌ 错误: {context}");
                    errorLog.AppendLine($"  异常类型: {ex.GetType().Name}");
                    errorLog.AppendLine($"  消息: {ex.Message}");
                    errorLog.AppendLine($"  堆栈跟踪:");
                    errorLog.AppendLine($"  {ex.StackTrace}");
                    if (ex.InnerException != null)
                    {
                        errorLog.AppendLine($"  内部异常: {ex.InnerException.Message}");
                    }
                    errorLog.AppendLine();

                    File.AppendAllText(LogFilePath, errorLog.ToString());
                    Debug.WriteLine(errorLog.ToString());
                }
            }
            catch (Exception logEx)
            {
                Debug.WriteLine($"写入错误日志失败: {logEx.Message}");
            }
        }

        /// <summary>
        /// 清理旧日志文件
        /// </summary>
        private static void CleanOldLogs(string directory)
        {
            try
            {
                if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
                    return;

                var logFiles = Directory.GetFiles(directory, "startup_log_*.txt");
                var cutoffDate = DateTime.Now.AddDays(-3);

                foreach (var file in logFiles)
                {
                    try
                    {
                        var fileInfo = new FileInfo(file);
                        if (fileInfo.LastWriteTime < cutoffDate)
                        {
                            File.Delete(file);
                        }
                    }
                    catch
                    {
                        // 忽略单个文件删除失败
                    }
                }
            }
            catch
            {
                // 清理失败不影响应用启动
            }
        }

        /// <summary>
        /// 记录启动成功
        /// </summary>
        public static void LogSuccess()
        {
            LogStep("✅ 应用启动成功");
            
            try
            {
                // 将当前日志重命名为带时间戳的文件
                if (File.Exists(LogFilePath))
                {
                    var directory = Path.GetDirectoryName(LogFilePath);
                    var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                    var archivePath = Path.Combine(directory ?? "", $"startup_log_{timestamp}.txt");
                    File.Copy(LogFilePath, archivePath, true);
                }
            }
            catch
            {
                // 归档失败不影响应用
            }
        }
    }
}
